package com.example.chengzhengwei;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class HistoryActivity extends AppCompatActivity {

    private LineChart chart;
    private List<LineDataSet> dataSets = new ArrayList<>();
    private Map<Integer, List<Entry>> channelDataMap = new HashMap<>();
    private CheckBox[] checkBoxes;
    private DatabaseHelper dbHelper;
    private int dataPointCount = 0;
    private final int[] CHANNEL_COLORS = {
            0xFF0000FF, 0xFFFF00FF, 0xFF00FF00, 0xFFFFFF00,
            0xFF00FFFF, 0xFF000080, 0xFF800080, 0xFF808000
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);

        dbHelper = new DatabaseHelper(this);
        initViews();
        initializeChart();
        loadHistoryData();

        Button buttonCancel = findViewById(R.id.buttonBack);
        Button buttonexprotusb = findViewById(R.id.buttonExport);


        buttonCancel.setOnClickListener(v -> {
            Intent intent = new Intent(HistoryActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        });
        buttonexprotusb.setOnClickListener(v -> {
            Intent intent = new Intent(HistoryActivity.this, ExportOptionsActivity.class);
            startActivity(intent);
            finish();
        });
    }

    private void initViews() {
        chart = findViewById(R.id.chart);
        checkBoxes = new CheckBox[8];

        checkBoxes[0] = findViewById(R.id.checkBox1);
        checkBoxes[1] = findViewById(R.id.checkBox2);
        checkBoxes[2] = findViewById(R.id.checkBox3);
        checkBoxes[3] = findViewById(R.id.checkBox4);
        checkBoxes[4] = findViewById(R.id.checkBox5);
        checkBoxes[5] = findViewById(R.id.checkBox6);
        checkBoxes[6] = findViewById(R.id.checkBox7);
        checkBoxes[7] = findViewById(R.id.checkBox8);

        // 设置CheckBox
        setupCheckBoxes();
    }

    private void setupCheckBoxes() {
        for (int i = 0; i < 8; i++) {
            CheckBox cb = checkBoxes[i];
            cb.setChecked(true);
            cb.setTextColor(CHANNEL_COLORS[i]);

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                cb.setButtonTintList(ContextCompat.getColorStateList(this,
                        getColorResourceForColor(CHANNEL_COLORS[i])));
            }

            final int channelIndex = i;
            cb.setOnClickListener(v -> updateChannelVisibility(channelIndex));
        }
    }

    private void initializeChart() {
        chart.getDescription().setEnabled(false);

        for (int i = 0; i < 8; i++) {
            LineDataSet dataSet = new LineDataSet(new ArrayList<>(), "通道" + (i + 1));
            dataSet.setColor(CHANNEL_COLORS[i]);
            dataSet.setLineWidth(2f);
            dataSet.setDrawCircles(true);
            dataSet.setDrawValues(false);
            dataSet.setVisible(true);

            dataSets.add(dataSet);
            channelDataMap.put(i, new ArrayList<>());
        }

        LineData lineData = new LineData();
        for (LineDataSet dataSet : dataSets) {
            lineData.addDataSet(dataSet);
        }
        chart.setData(lineData);
        Legend legend = chart.getLegend();
        legend.setEnabled(false);
        // 额外设置，确保图例完全隐藏
        legend.setForm(Legend.LegendForm.NONE);
        legend.setTextSize(0f);
        // 配置X轴
        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                int index = (int) value;
                if (index < dataPointCount) {
                    // 假设每个数据点间隔15秒
                    int seconds = index * 15;
                    if (seconds < 60) return seconds + "s";
                    int mins = seconds / 60;
                    int secs = seconds % 60;
                    return String.format("%d:%02d", mins, secs);
                }
                return "";
            }
        });

        // 配置Y轴
        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setAxisMinimum(0f);
        leftAxis.setAxisMaximum(160000f);
        leftAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return String.format("%.0f", value);
            }
        });

        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setEnabled(false);

        chart.invalidate();
    }

    private void loadHistoryData() {
        List<RunData> historyData = dbHelper.getRunData();
        if (historyData.isEmpty()) {
            Toast.makeText(this, "没有历史数据", Toast.LENGTH_SHORT).show();
            return;
        }

        // 按通道分组整理数据
        Map<Integer, List<RunData>> channelData = new HashMap<>();
        for (int i = 0; i < 8; i++) {
            channelData.put(i, new ArrayList<>());
        }

        for (RunData data : historyData) {
            channelData.get(data.getChannel()).add(data);
        }

        // 填充图表数据
        for (int i = 0; i < 8; i++) {
            List<RunData> channelDataList = channelData.get(i);
            List<Entry> entries = channelDataMap.get(i);

            for (int j = 0; j < channelDataList.size(); j++) {
                RunData data = channelDataList.get(j);
                entries.add(new Entry(j, data.getValue()));
            }

            dataSets.get(i).setValues(entries);
        }

        dataPointCount = historyData.size() / 8; // 假设每个通道数据点数量相同
        updateXAxisLabelCount();

        chart.getData().notifyDataChanged();
        chart.notifyDataSetChanged();
        chart.invalidate();
    }

    private void updateChannelVisibility(int channelIndex) {
        CheckBox cb = checkBoxes[channelIndex];
        LineDataSet dataSet = dataSets.get(channelIndex);
        dataSet.setVisible(cb.isChecked());

        chart.getData().notifyDataChanged();
        chart.notifyDataSetChanged();
        chart.invalidate();
    }

    private void updateXAxisLabelCount() {
        XAxis xAxis = chart.getXAxis();
        xAxis.setLabelCount(Math.min(dataPointCount, 8), false);
    }

    private int getColorResourceForColor(int color) {
        switch (color) {
            case 0xFF0000FF: return R.color.channel1;
            case 0xFFFF00FF: return R.color.channel2;
            case 0xFF00FF00: return R.color.channel3;
            case 0xFFFFFF00: return R.color.channel4;
            case 0xFF00FFFF: return R.color.channel5;
            case 0xFF000080: return R.color.channel6;
            case 0xFF800080: return R.color.channel7;
            case 0xFF808000: return R.color.channel8;
            default: return android.R.color.holo_blue_dark;
        }
    }
}